package hhm.android.http;

import android.util.Base64;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

public class ASEJava {

    public static String aesEncrypt(String sSrc) throws Exception {
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        byte[] raw = "hM8qR0kB3bC6pO9z".getBytes();
        SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
        IvParameterSpec iv = new IvParameterSpec("xS5xP9hJ0jG1cI6e".getBytes());
        //使用CBC模式，需要一个向量iv，可增加加密算法的强度
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
        byte[] encrypted = cipher.doFinal(sSrc.getBytes());
        //此处使用BASE64做转码。
        return byte2Base64StringFun(encrypted);
    }

    public static String aesDecrypt(String sSrc) throws Exception {
        byte[] raw = "hM8qR0kB3bC6pO9z".getBytes();
        SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        IvParameterSpec iv = new IvParameterSpec("xS5xP9hJ0jG1cI6e".getBytes());
        cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
        //先用base64解密
        byte[] encrypted1 = base64String2ByteFun(sSrc);
        byte[] original = cipher.doFinal(encrypted1);
        return new String(original);
    }

    //base64字符串转byte[]
    public static byte[] base64String2ByteFun(String base64Str) {
        return Base64.decode(base64Str, Base64.NO_WRAP);
    }

    //byte[]转base64
    public static String byte2Base64StringFun(byte[] b) {
        return Base64.encodeToString(b, Base64.NO_WRAP);
    }

}
